<script setup lang="tsx">
import {
  businessEnterApplyListApi,
  businessEnterApplyAuditApi,
  merchantSubAcctOpenApi,
  merchantOpenApi
} from '@/api/merchantManagement'
import { businessEnterApply } from '@/api/merchantManagement/types'
import Detail from './components/Detail.vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { AuditStateDict, CompanyTypeDict, SystemAuditStateDict, dictToList } from '@/utils/dict'
import { useValidator } from '@/hooks/web/useValidator'
import { Form, FormSchema } from '@/components/Form'
import tick from '/@/assets/imgs/tick.png'

const { t } = useI18n()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await businessEnterApplyListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      auditState: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '待审核',
    value: 1
  },
  {
    label: '审核通过',
    value: 2
  },
  {
    label: '审核不通过',
    value: 3
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'applyNo',
    label: '申请编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 210
    }
  },
  {
    field: 'businessShortName',
    label: '商家简称',
    search: {
      componentProps: {
        placeholder: '请输入商家简称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>
                <img class={'w-10 mr-3'} src={row.logo} />
                <span>{row.businessShortName}</span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'adminName',
    label: '超级管理员',
    search: {
      componentProps: {
        placeholder: '请输入超管姓名/手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.mobile}</div>
              <div>{row.nickName}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'businessName',
    label: '企业名称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessProvinceName',
    label: '所属省',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessCityName',
    label: '所属市',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessAddress',
    label: '详细地址',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'auditState',
    label: t('userDemo.status'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.auditState && AuditStateDict[row.auditState]}</div>
              <span>{row.systemAuditState && SystemAuditStateDict[row.systemAuditState]}</span>
              {row.auditState === 3 && <span>+原因：{row.refuseReason}</span>}
            </>
          )
        }
      }
    }
  },
  {
    field: 'companyType',
    label: '类型',
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(CompanyTypeDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.companyType && CompanyTypeDict[row.companyType]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'applyTime',
    label: '申请时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 180
    }
  },
  {
    field: 'auditTime',
    label: '审核时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 180
    }
  },
  // {
  //   field: 'createTime',
  //   label: '入驻时间',
  //   search: {
  //     component: 'DatePicker',
  //     componentProps: {
  //       type: 'datetime',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   table: {
  //     width: 220
  //   }
  // },
  // {
  //   field: 'systemAuditState',
  //   label: '系统审核状态',
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     hidden: true
  //   },
  //   table: {
  //     width: 210,
  //     slots: {
  //       default: (data: any) => {
  //         const row = data.row as any
  //         return (
  //           <>
  //             <span>{row.systemAuditState && SystemAuditStateDict[row.systemAuditState]}</span>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 190,
      slots: {
        default: (data: any) => {
          const row = data.row as businessEnterApply
          if (row.auditState === 1 && row.systemAuditState === 1) {
            return (
              <>
                <ElButton
                  v-hasPermi="POST /businessEnterApply/audit"
                  type="primary"
                  link
                  onClick={() => {
                    details(row)
                    setTimeout(() => {
                      setValues({
                        financialAccountType: row.financialAccountType || 1
                      })
                    }, 500)
                  }}
                >
                  审核
                </ElButton>
              </>
            )
          }
          if (row.auditState === 1 && (row.systemAuditState === 5 || row.systemAuditState === 7)) {
            return (
              <>
                <div class="pop-box">
                  <ElButton
                    v-hasPermi="POST /businessEnterApply/merchantOpen"
                    type="primary"
                    link
                    onClick={() => details(row)}
                  >
                    开通商户业务
                  </ElButton>
                  <ElButton
                    v-hasPermi="GET /businessEnterApply/details"
                    type="primary"
                    link
                    onClick={() => details(row, true)}
                  >
                    查看详情
                  </ElButton>
                  {isShowPop.value && showPopId.value === row.id && (
                    <div style="width: 129px;height: 63px;background: #fff;border-radius: 4px;border: 1px solid #ccc;">
                      <div
                        style="display: flex;justify-content: space-between;align-items: center;height: 50%;padding: 0 10px;cursor: pointer;"
                        onClick={() => handleChangeCallState(row, 1)}
                      >
                        <span>接口开通</span>
                        {callState.value === 1 && (
                          <img src={tick} alt="" style="width: 7px;height: 7px;" />
                        )}
                      </div>
                      <div
                        style="display: flex;justify-content: space-between;align-items: center;height: 50%;padding: 0 10px;cursor: pointer;"
                        onClick={() => handleChangeCallState(row, 2)}
                      >
                        <span>汇付控台开通</span>
                        {callState.value === 2 && (
                          <img src={tick} alt="" style="width: 7px;height: 7px;" />
                        )}
                      </div>
                      <div></div>
                      <div></div>
                    </div>
                  )}
                </div>
              </>
            )
          }
          if (row.auditState === 1 && (row.systemAuditState === 9 || row.systemAuditState === 11)) {
            return (
              <>
                <ElButton
                  v-hasPermi="POST /businessEnterApply/merchantSubAcctOpen"
                  type="primary"
                  link
                  onClick={() => details(row)}
                >
                  开通子账号
                </ElButton>
                <ElButton
                  v-hasPermi="GET /businessEnterApply/details"
                  type="primary"
                  link
                  onClick={() => details(row, true)}
                >
                  查看详情
                </ElButton>
              </>
            )
          }
          return (
            <>
              <ElButton
                v-hasPermi="GET /businessEnterApply/details"
                type="primary"
                link
                onClick={() => details(row, true)}
              >
                查看详情
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const isShowPop = ref(false)
const showPopId = ref(0)
const callState = ref(0)

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  console.log(params)
  const { applyTime, auditTime, ...rest } = params
  let startApplyTime, endApplyTime, startAuditTime, endAuditTime
  if (applyTime && applyTime.length > 0) {
    startApplyTime = applyTime[0]
    endApplyTime = applyTime[1]
  }
  if (auditTime && auditTime.length > 0) {
    startAuditTime = auditTime[0]
    endAuditTime = auditTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startApplyTime,
    endApplyTime,
    startAuditTime,
    endAuditTime,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

// const delLoading = ref(false)
// const ids = ref<number[]>([])

const detailId = ref(0)
const auditState = ref(0)
const systemAuditState = ref(0)

const handleChangeCallState = (row: any, i) => {
  console.log(row.id)
  callState.value = i
  ElMessageBox.confirm(
    '请确认已在汇付控台开通商家微信支付、余额支付、网银功能。确认后即视为业务开通成功，无法变更。'
  )
    .then(async () => {
      console.log('确定')
      const setData = {
        id: row.id,
        callState: i
      }
      const res = await merchantOpenApi(setData)
      console.log(res)
      isShowPop.value = false
      currentPage.value = 1
      getList()
    })
    .catch(() => {
      // catch error
      console.log('取消')
      isShowPop.value = false
    })
}

const details = async (row: any, isDetail) => {
  if (!isDetail) {
    if (row.auditState === 1 && (row.systemAuditState === 5 || row.systemAuditState === 7)) {
      callState.value = 0
      isShowPop.value = showPopId.value === row.id ? !isShowPop.value : true
      showPopId.value = row.id
      // console.log(isShowPop.value)
      return
    }
    if (row.auditState === 1 && (row.systemAuditState === 9 || row.systemAuditState === 11)) {
      ElMessageBox.confirm('是否开通子账号？')
        .then(async () => {
          const res = await merchantSubAcctOpenApi(row.id)
          console.log(res)
          currentPage.value = 1
          getList()
        })
        .catch(() => {
          // catch error
          console.log('取消')
        })
      return
    }
  }
  console.log(row)
  detailId.value = row.id
  auditState.value = row.auditState
  systemAuditState.value = row.systemAuditState
  showDrawer.value = true
}

const { formRegister, formMethods } = useForm()
const { getFormData, setSchema, setValues } = formMethods

const { required, lengthRange } = useValidator()

const rules = reactive({
  financialAccountType: [required()],
  auditState: [required()],
  refuseReason: [required(), lengthRange({ min: 0, max: 50 })]
})

const auditSchemas = reactive<FormSchema[]>([
  {
    field: 'financialAccountType',
    label: '结算类型：',
    colProps: {
      span: 24
    },
    component: 'RadioGroup',
    componentProps: {
      // modelValue: 1,
      options: [
        {
          label: '自建账户',
          value: 1
        },
        {
          label: '结算池',
          value: 2
        }
      ],
      on: {
        change: (val) => {
          console.log({ val })
          // setSchema([
          //   {
          //     field: 'financialAccountType',
          //     modelValue: val
          //   }
          // ])
          // setValues({
          //   financialAccountType: val
          // })
        }
      }
    },
    formItemProps: {
      labelWidth: 100
    }
  },
  {
    field: 'auditState',
    label: '审核结果：',
    colProps: {
      span: 24
    },
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '审核通过',
          value: 2
        },
        {
          label: '审核不通过',
          value: 3
        }
      ],
      on: {
        change: (val) => {
          setSchema([
            {
              field: 'refuseReason',
              path: 'hidden',
              value: val === 2
            }
          ])
          if (val === 2) {
            setValues({
              refuseReason: null
            })
          }
        }
      }
    },
    formItemProps: {
      labelWidth: 100
    }
  },
  {
    field: 'refuseReason',
    label: '不通过原因：',
    hidden: true,
    colProps: {
      span: 24
    },
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 5,
      style: {
        width: 100
      }
    },
    formItemProps: {
      labelWidth: 100
    }
  }
])

const saveLoading = ref(false)

const save = async () => {
  const formData = await getFormData()
  if (!formData.financialAccountType) {
    ElMessage.error('请选择结算类型')
    return
  }
  if (Object.keys(formData).length === 0) {
    ElMessage.error('请选择审核结果')
    return
  }
  if (formData.auditState === 3 && !('refuseReason' in formData)) {
    ElMessage.error('请填写不通过原因')
    return
  }
  if (formData.auditState === 3 && formData.refuseReason.length > 50) {
    ElMessage.error('不通过原因请勿超过50字')
    return
  }
  saveLoading.value = true
  const res = await businessEnterApplyAuditApi({
    id: unref(detailId),
    ...unref(formData)
  })
  console.log(res)
  saveLoading.value = false
  showDrawer.value = false
  getList()
  // if (res.code === 200) {
  //   ElMessage.success(t('toast.saveSuccess'))
  // } else {
  //   ElMessage.error(res.message)
  // }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <!-- <div class="mb-10px">
            <ElButton v-hasPermi="'POST /admin/user/create'" type="primary" @click="AddAction">{{
              t('exampleDemo.add')
            }}</ElButton>
          </div> -->
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>

    <ElDrawer
      title="商家入驻详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
      <Form
        v-if="auditState === 1 && systemAuditState === 1"
        :rules="rules"
        :schema="auditSchemas"
        label-width="240"
        @register="formRegister"
      />
      <template #footer v-if="auditState === 1 && systemAuditState === 1">
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
        <ElButton @click="showDrawer = false">{{ t('dialogDemo.close') }}</ElButton>
      </template>
    </ElDrawer>
  </div>
</template>

<style lang="less" scoped>
.pop-box {
  .pop {
    width: 129px;
    height: 63px;
    background: #fff;
    border: 1px solid #999;
    border-radius: 4px;
  }
}

/deep/.el-popper {
  max-width: 300px !important;
}
</style>
